package start.queue;

import sun.misc.Request;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Queue {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> requestQueue = new LinkedBlockingQueue<>();

        // 消费者线程
        new Thread(() -> {
            try {
                while (true) {
                    String request = requestQueue.take(); // 阻塞直到有元素
                    Thread.sleep(1000*1);
                    System.out.println("Thread 1(1秒) ### Received request: " + request);
                }
                // 处理请求
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
            }
        }).start();

        // 消费者线程
        new Thread(() -> {
            try {
                while (true) {
                    String request = requestQueue.take(); // 阻塞直到有元素
                    Thread.sleep(500);
                    System.out.println("Thread 2(0.5秒) ### Received request: " + request);
                }
                // 处理请求
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
            }
        }).start();

        // 消费者线程
        new Thread(() -> {
            try {
                while (true) {
                    String request = requestQueue.take(); // 阻塞直到有元素
                    Thread.sleep(2000);
                    System.out.println("Thread 3(2秒) ### Received request: " + request);
                }
                // 处理请求
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
            }
        }).start();

        // 生产者线程
        new Thread(() -> {
            try {
                //100次的循环
                for (int i = 0; i < 100; i++) {
                    requestQueue.put("当前元素：" + i); // 阻塞直到有空间
                    Thread.sleep(100);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 恢复中断状态
            }
        }).start();

    }
}
